<?php

class cntrlbookeditor implements viewController {

	private $area;
	private $side;
	private $dependencies = array("JavaScript" => array("facebox.js", "bookEditor.js"), "CSS" => array("facebox.css"));
	private $pageName = "";
	private $userObj;
	private $thisID;
	
	public function __construct(user &$userObj){

		if( $userObj->getAccessLevel() == -1 ){
			header("Location: home");
			exit;
		}
		
		$this->side = new template('control.editBook');
		$this->area = new template('area.bookEditor');

		$this->userObj = $userObj;
		
		parse_str( $_GET['act'] );

		$bookInfo = book::getBook($userObj, $id);

		$this->thisID = $id;

		$this->renderPage($id, $bookInfo);
		$this->renderBookList();
	}

	private function renderPage($id, $bookInfo){
		$id = (int)$id;		
		
		$this->area->replaceAll(array(
			"bookName" => $bookInfo['name'],
			"groupDescription" => $bookInfo['description'],
			"bID" => $bookInfo['bID']
		));
		
		$charts = chart::getBookCharts($this->thisID, 200);
		
		$row = new template('fragment.bookList');
		
		$tableBody = "";
		
		$i = 1;
		
		// Render the charts in the book.
		foreach($charts as &$chart){
			$library = chart::getChartLibrary((int)$chart['chID']);
			$chart['library'] = $library;
			
			$row->replaceAll(array(
				"page" => ($chart['chartPosition'] != "" ? $chart['chartPosition'] : $i),
				"chart" => $chart['name'],
				"library" => $chart['library'],
				"author" => $chart['belongsTo'],
				"chID" => $chart['chID'],
				"thumb" => ($chart['thumbnail'] != "") ? "{absolute-url}imageStore/thumbnails/" . $this->userObj->getuID() . "/" . $chart['thumbnail'] : ""
			));
			
			$i++;
			
			$tableBody .= $row->get();
			$row->reset();
		}
		
		$this->area->replace('tableBody', $tableBody);
		
	}

	protected function renderBookList(){
		$books = book::getBookList($this->userObj->getuID(), 0, 500);
	
		$output = "";
		
		foreach($books as $book){
			if($this->thisID == $book['bID']){
				$output .= "<option value='" . $book['bID'] . "' selected='selected'>" . $book['name'] . "</option>\n";
			} else {
				$output .= "<option value='" . $book['bID'] . "'>" . $book['name'] . "</option>\n";
			}
		}
		
		$this->side->replace('groupList', $output);
	}

	public function getSide(){
		return $this->side;
	}
	
	public function getArea(){
		return $this->area;
	}
	
	public function getDependencies(){
		return $this->dependencies;
	}

	public function getPageName(){
		return $this->pageName;
	}
	
	public function getTools(){
		return "";
	}

}

?>